package com.luocc.ccdemo.vm

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.luocc.ccdemo.db.UserRepository
import com.luocc.ccdemo.entity.Result
import com.luocc.ccdemo.entity.User
import kotlinx.coroutines.launch

class UserViewModel(application: Application) : AndroidViewModel(application) {

    private val mUserRepository: UserRepository = UserRepository()
    private val mRegisterResult: MutableLiveData<Result<Boolean>> = MutableLiveData()
    private val mLoginResult: MutableLiveData<Result<String>> = MutableLiveData()
    private val mLogoutResult: MutableLiveData<Result<Boolean>> = MutableLiveData()

    fun login(user: User) {
        viewModelScope.launch {
            try {
                val result = mUserRepository.login(user)
                mLoginResult.value = result
            } catch (e: Exception) {
                mLoginResult.value = Result("", -1, "服务器异常")
            }
        }
    }

    fun logout() {
        viewModelScope.launch {
            try {
                val result = mUserRepository.logout()
                mLogoutResult.value = result
            } catch (e: Exception) {
                mLogoutResult.value = Result(false, -1, "服务器异常")
            }
        }
    }

    fun register(username: String, password: String, rePassword: String) {
        viewModelScope.launch {
            try {
                val register = mUserRepository.register(username, password, rePassword)
                mRegisterResult.value = register
            } catch (e: Exception) {
                mRegisterResult.value = Result(false, -1, "服务器异常")
            }
        }
    }

    fun getRegisterResult(): LiveData<Result<Boolean>> {
        return mRegisterResult
    }

    fun getLoginResult(): LiveData<Result<String>> {
        return mLoginResult
    }

    fun getLogoutResult(): LiveData<Result<Boolean>> {
        return mLogoutResult
    }
}